package ks.server.controllers.commands.general.user;

import java.util.Vector;

import ks.framework.common.Message;
import ks.framework.communicator.Communicator;
import ks.framework.interfaces.IProcessMessage;
import ks.managers.user.User;
import ks.server.ipc.Listener;
import ks.server.persist.PersistentUserManager;
import ks.server.ServerContext;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

/**
 * Process command to retrieve information on a particular user.
 * 
 * @author Christopher Page
 */
public class UserInfoController implements IProcessMessage {

	/** Primary agent to whom we can communicate our messages. */
	Communicator com;
	
	public UserInfoController (Communicator com) {
		this.com = com;
	}
	
	/**
	 * Process the message
	 * 
	 * @param m The message to process.
	 * @return A boolean value.
	 */
	public boolean process(Message m) {
		PersistentUserManager um = ServerContext.getUserManager();
		
		Vector<User> players = new Vector<User>(0);
		NodeList playernamesNodeList = m.contents().getChildNodes();
		Node tmpNode;
		User tmpUser;
		
		for (int i = 0; i < playernamesNodeList.getLength(); i++) {
			tmpNode = playernamesNodeList.item(i).getAttributes().getNamedItem("name");
			
			if (tmpNode != null) {
				tmpUser = um.getUser(tmpNode.getNodeValue());
				if (tmpUser != null)
					players.add(tmpUser);
				else {
					Listener.nack(m, 4, "User, " + tmpNode.getNodeValue() + ", does not exist.");
					return false;
				}
			}
			else {
				Listener.nack(m, 4, "Badly formatted data recieved.");
				return false;
			}
		}
		
		Listener.ack(m, "Successfully recieved list of users to retrieve info about.");
		
		StringBuilder sb = new StringBuilder("<request version='1.0' id='589a39591271844e3fbe32bbb9281ad9'>");
		for (User u : players) {
			sb.append("<account-update player=\"" + u.getName() + "\" icon=\"" + u.getIconName() + "\" rating=\"" + u.getRating() + "\" />");
		}
		sb.append("</request>");
		
		Document d = Message.construct(sb.toString());
		Message r = new Message(d);
		r.setRecipient(m.getOriginator());
		return com.distribute(r);
	}
}
